package com.deep.nacos.track.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {
    private static Logger log = LoggerFactory.getLogger(TestController.class);

    private final RestTemplate restTemplate;

    @Autowired
    public TestController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @RequestMapping("/")
    public String home() {
        log.info("Handling home");
        return "Hello World";
    }

    @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
    public String echo(@PathVariable String str) {
        return restTemplate.getForObject("http://tcc-nacos-provider/echo/" + str, String.class);
    }

    @RequestMapping(value = "/config/{str}", method = RequestMethod.GET)
    public String config(@PathVariable String str) {
        return restTemplate.getForObject("http://tcc-nacos-provider/config/get/" + str, String.class);
    }


    /**
     * hystrix 调用 timeout
     * @param string
     * @return
     * @throws InterruptedException
     */
    @RequestMapping(value = "/echo2/{string}", method = RequestMethod.GET)
    public String echo2(@PathVariable String string) throws InterruptedException {
        Thread.sleep(100000);
        return "timeout =  " + string;
    }

    /**
     * hystrix 调用 异常
     * @param string
     * @return
     * @throws InterruptedException
     */
    @RequestMapping(value = "/echo3/{string}", method = RequestMethod.GET)
    public String echo3(@PathVariable String string) throws Exception {
        throw new Exception("hystrix exception " + string);
//        return "Hello Nacos Discovery " + string;
    }

//    @RequestMapping(value = "/hello/{string}", method = RequestMethod.GET)
//    public String hello(@PathVariable String string) throws Exception {
//        return "Hello Nacos Discovery Sentinel =  " + string;
//    }

    @GetMapping(value = "/hello/{str}", produces = "application/json")
    public String hello(@PathVariable String str) {
        log.info("-----------收到消费者请求-----------");
        log.info("收到消费者传递的参数：" + str);
        String result = "我是服务提供者，见到你很高兴==>" + str;
        log.info("提供者返回结果：" + result);
        return result;
    }
}